import json
from django.db.models import QuerySet
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.db.models import Q
import re
from django.urls import reverse
from Web.models import *

dyn = ['0', '三皇五帝', '夏朝', '商朝', '西周', '东周', '秦朝', '西汉', '东汉', '三国', '西晋',
       '东晋', '南北朝', '隋朝', '唐朝', '五代', '北宋', '南宋', '元朝', '明朝', '清朝', '近代']


# Create your views here.

def homepage(request):
    # 查询各个朝代的
    dynn = dyn[1:]
    context1 = {'state': True}
    context2 = {'state': False}
    for i in dynn:
        bookli = AllBook.objects.filter(dynasty=i).filter(checkBool=1)
        booklii = []
        for j in bookli:
            booklii.append({'name': j.bookName, "intro": j.intro, "id": j.id})
        if len(booklii) > 5:
            bookliii = booklii[0:5]
        else:
            bookliii = booklii[0:]
        context1[i] = bookliii
        context2[i] = bookliii
    try:
        name = request.get_signed_cookie(key='name', salt='rxg')
        username = AccountNumber.objects.filter(account=name).first().userName
        context1["name"] = username
        # print(context1["西汉"])
        return render(request, 'homepage.html', context=context1)
    except Exception:
        return render(request, 'homepage.html', context=context2)


def login(request):
    if request.method == 'GET':
        try:
            name = request.get_signed_cookie(key='name', salt='rxg')
            rev = reverse('web:homepage')
            return HttpResponseRedirect(rev)
        except Exception:
            res = render(request, 'login.html')
            return res
    if request.method == 'POST':
        postdata = request.POST
        name = postdata.get('name')
        password = postdata.get('password')
        pattern = re.compile('\\w*')
        if pattern.fullmatch(name) and pattern.fullmatch(password):  # 检查用户名和密码是否符合格式
            pass
        else:
            return render(request, 'failing_login.html', context={"reason": "名字或密码不符合格式！"})
        if not 6 <= len(name) <= 16:  # 名字长度
            return render(request, 'failing_login.html', context={"reason": "账号长度不符合要求！"})
        if not 6 <= len(password) <= 16:  # 密码长度
            return render(request, 'failing_login.html', context={"reason": "密码长度不符合要求！"})
        rec = AccountNumber.objects.filter(account=name).first()  # 在数据库查找这个账号信息
        if rec is not None:
            if rec.password == password:  # 登陆成功，返回首页,并且设置cookie
                url = reverse('web:homepage')
                res = HttpResponseRedirect(url)
                res.set_signed_cookie(key='name', value=name, salt='rxg')
                return res
            else:
                rep = render(request, 'failing_login.html', context={'reason': '密码错误'})
                rep.set_signed_cookie(key='name', value=name, salt='rxg', max_age=3 * 60)
                return render(request, 'failing_login.html', context={'reason': '密码错误'})
        else:
            return render(request, 'failing_login.html', context={'reason': '账号不存在'})


def register(request):
    if request.method == 'GET':  # 如果是get请求，就返回注册页面
        return render(request, 'register.html')
    elif request.method == 'POST':  # 如果是post请求，就处理用户上传的数据
        postdata = request.POST
        name = postdata.get('name')
        nicheng = postdata.get('nicheng')
        password1 = postdata.get('password1')
        password2 = postdata.get('password2')
        pattern = re.compile('\\w*')
        if pattern.fullmatch(name) and pattern.fullmatch(password1) and pattern.fullmatch(password2):  # 检查用户名和密码是否符合格式
            pass
        else:
            return render(request, 'failing_resault.html', context={"reason": "名字或密码不符合格式！"})
        if password2 == password1:  # 两次密码是否相等
            pass
        else:
            return render(request, 'failing_resault.html', context={"reason": "两次密码不相同！"})
        if not 6 <= len(name) <= 16:  # 名字长度
            return render(request, 'failing_resault.html', context={"reason": "账号长度不符合要求！"})
        if not 6 <= len(password1) <= 16:  # 密码长度
            return render(request, 'failing_resault.html', context={"reason": "密码长度不符合要求！"})
        if len(nicheng) > 16 or len(nicheng) < 1:
            return render(request, 'failing_resault.html', context={"reason": "昵称长度不符合要求！"})
        data = AccountNumber()
        account = AccountNumber.objects.filter(account=name)
        if account.first() is not None:
            return render(request, 'failing_resault.html', context={"reason": "账号已经存在！"})
        data.account = name
        data.password = password1
        data.userName = nicheng
        data.save()
        return render(request, 'success_regist.html')


def personal_center(request):
    try:
        name = request.get_signed_cookie(key='name', salt='rxg')
        name1 = AccountNumber.objects.filter(account=name).first().userName
        return render(request, 'personal_center.html', context={'name': name1})
    except Exception:
        res = reverse('web:login')
        return HttpResponseRedirect(res)


def logout(request):
    res = HttpResponseRedirect(reverse("web:homepage"))
    res.delete_cookie(key="name")
    return res


# 上传
def upload(request):
    if request.method == "GET":
        try:
            name = request.get_signed_cookie(key='name', salt='rxg')
            username = AccountNumber.objects.filter(account=name).first().userName
            return render(request, 'upload.html', context={'name': username})
        except Exception:
            return render(request, 'login.html')
    elif request.method == 'POST':
        user_name = request.get_signed_cookie(key='name', salt='rxg')  # 通过cookies获取用户账号
        accountnumber = AccountNumber.objects.filter(account=user_name).first()
        author = request.POST.get('author')
        if len(author) == 0:
            return HttpResponse("没有作者")
        book_name = request.POST.get('book_name')
        if len(book_name) == 0:
            return HttpResponse("没有作品名")
        intro = request.POST.get('intro')
        translation = request.POST.get('translation')
        dynasty_id = request.POST.get('radiode')
        if dynasty_id is None:
            return HttpResponse("没有选择类型")
        dynasty = dyn[int(dynasty_id)]
        book_content = request.POST.get('book_content')
        bname = AllBook.objects.filter(bookName=book_name).first()  # 在数据库中查询是否有这本书了
        # uname = AccountNumber.objects.filter(number=user_name).first()
        if len(book_content) == 0:
            return HttpResponse("作品内容不能是空")
        if bname is None:
            print("内容是：", book_content)
            data = AllBook()
            data.upAccount = accountnumber
            data.bookName = book_name
            data.intro = intro
            data.translation = translation
            data.bookContent = book_content
            data.dynasty = dynasty
            data.author = author
            data.save()
            return HttpResponse("上传成功")
        else:
            return HttpResponse('书名已经存在了')


# 将提交的插入到指定的数据库里面


def app(request):
    password = "culture"
    print("method", request.method)
    encrypt = [{"summary": "asdasdasd", "dynasty": "asdasdasd", "imagePath": "sdfsdfsdf"}]
    resault = {"type": "culture", "data": encrypt}
    return HttpResponse(json.dumps(resault), content_type='application/json')


def testpost(request):
    print("方法是：", request.method)
    if request.method == 'POST':
        data = request.body
        # data1 = json.loads(str(data))
        # data2 = data1.get('name')
        print("接受到的数据是：", data)
        return HttpResponse(data)
    else:
        return HttpResponse("方法不为post")


def backgroundlogin(request):
    if request.method == 'GET':
        try:
            ck = request.get_signed_cookie(key='admin_name', salt="rxg")
            if ck == 'admin':
                return HttpResponseRedirect(reverse('web:background'))
        except Exception:
            return render(request, 'backgroundlogin.html')
    if request.method == 'POST':
        postdata = request.POST
        name = postdata.get('name')
        password = postdata.get('password')
        if name == 'admin':
            pass
        else:
            return HttpResponse("用户名错误")
        if password == 'password':
            pass
        else:
            return HttpResponse('密码错误')
        if name == 'admin' and password == 'password':
            rev = reverse('web:background')
            res = HttpResponseRedirect(rev)
            res.set_signed_cookie(key='admin_name', value=name, salt='rxg')
            rev = reverse('web:background')
            return res


def background(request):
    if request.method == 'GET':
        try:
            ck = request.get_signed_cookie(key='admin_name', salt="rxg")
            if ck == 'admin':
                return HttpResponseRedirect(reverse('web:check'))
        except Exception:
            return HttpResponseRedirect(reverse('web:backgroundlogin'))


def check(request):
    try:
        ck = request.get_signed_cookie(key='admin_name', salt="rxg")
        if ck == 'admin':
            pass
        else:
            return HttpResponse("账户名称不是admin")
        uf = AllBook.objects.filter(checkBool=2)
        # 字典
        # 一个二元的数组，里面的元素分别保存着上传者和上传者的书名
        con = []
        for i in uf:
            con.append({'id': int(i.id), 'name': i.upAccount.account, 'book': i.bookName})
        return render(request, "check.html", {"c": con})
    except Exception:
        res = reverse('web:backgroundlogin')
        return HttpResponseRedirect(res)


def checkpage(request, idd):  # 书的详细审核页面
    try:
        ck = request.get_signed_cookie(key='admin_name', salt="rxg")
        if ck == 'admin':
            pass
        else:
            return HttpResponse("账户名称不是admin")
        txt = AllBook.objects.filter(id=idd).first()
        author = txt.author
        cont = txt.bookContent
        bookname = txt.bookName
        translation = txt.translation
        intro = txt.intro
        dynasty = txt.dynasty
        upname = txt.upAccount.account
        upnicheng = txt.upAccount.userName
        conli = cont.split('\n')
        introli = intro.split('\n')
        translationli = translation.split('\n')
        if txt is not None:
            con = {'name': bookname, 'author': author, 'dynasty': dynasty, "intro": introli,
                   'context': conli, 'translation': translationli, 'idd': idd, 'upname': upname,
                   'upnicheng': upnicheng}
            return render(request, 'checkpage.html', con)
        else:
            return HttpResponse("这本书不存在")
    except Exception:
        res = reverse('web:backgroundlogin')
        return HttpResponseRedirect(res)


def insert(request):
    if request.method == "POST":
        bookid = request.POST.get('idd')
        sta = request.POST.get('radiode')
        text = request.POST.get("reason")
        if int(sta) == 1:  # 不通过
            s = AllBook.objects.filter(id=bookid).first()
            s.checkBool = 3
            s.pReason = text
            s.save()
            return HttpResponse("不通过操作成功")
        elif int(sta) == 2:  # 通过
            s = AllBook.objects.filter(id=bookid).first()
            s.checkBool = 1
            s.save()
            return HttpResponse("通过操作成功")
    else:
        return HttpResponseRedirect(reverse('web:homepage'))


def look(request, idd):
    # bookli = AllBook.objects.filter(dynasty=dyn[int(idd)])
    # booklist = []
    # for i in bookli:
    #     booklist.append({"name": i.bookName, "author": i.author, "book_id": i.id})
    # dyn = ['0', '三皇五帝', '夏朝', '商朝', '西周', '东5周', '秦朝', '西7汉', '东8汉', '三国', '西10晋',
    #        '东11晋', '南北朝', '隋朝', '唐朝', '五15代', '北16宋', '南17宋', '元18朝', '明朝', '清朝', '近代']
    if int(idd) == 5:
        zuopinli = AllBook.objects.filter(
            Q(dynasty=dyn[1]) | Q(dynasty=dyn[2]) |
            Q(dynasty=dyn[3]) | Q(dynasty=dyn[4]) | Q(dynasty=dyn[5])).filter(checkBool=1)
        zuopinlii = []
        for i in zuopinli:
            zuopinlii.append({'name': i.bookName, "intro": i.intro, "id": i.id})
        return render(request, 'look.html', context={"zuopin": zuopinlii, 'dynasty': "先秦"})

    if int(idd) == 7:
        zuopinli = AllBook.objects.filter(
            Q(dynasty=dyn[7]) | Q(dynasty=dyn[8])).filter(checkBool=1)
        zuopinlii = []
        for i in zuopinli:
            zuopinlii.append({'name': i.bookName, "intro": i.intro, "id": i.id})
        return render(request, 'look.html', context={"zuopin": zuopinlii, 'dynasty': "汉朝"})

    if int(idd) == 10:
        zuopinli = AllBook.objects.filter(
            Q(dynasty=dyn[10]) | Q(dynasty=dyn[11])).filter(checkBool=1)
        zuopinlii = []
        for i in zuopinli:
            zuopinlii.append({'name': i.bookName, "intro": i.intro, "id": i.id})
        return render(request, 'look.html', context={"zuopin": zuopinlii, 'dynasty': "两晋"})
    if int(idd) == 16:
        zuopinli = AllBook.objects.filter(
            Q(dynasty=dyn[16]) | Q(dynasty=dyn[17])).filter(checkBool=1)
        zuopinlii = []
        for i in zuopinli:
            zuopinlii.append({'name': i.bookName, "intro": i.intro, "id": i.id})
        return render(request, 'look.html', context={"zuopin": zuopinlii, 'dynasty': "两宋"})
    if int(idd) == 18:
        zuopinli = AllBook.objects.filter(
            Q(dynasty=dyn[18]) | Q(dynasty=dyn[19]) | Q(dynasty=dyn[20])).filter(checkBool=1)
        zuopinlii = []
        for i in zuopinli:
            zuopinlii.append({'name': i.bookName, "intro": i.intro, "id": i.id})
        return render(request, 'look.html', context={"zuopin": zuopinlii, 'dynasty': "元明清"})

    zuopinli = AllBook.objects.filter(dynasty=dyn[int(idd)]).filter(checkBool=1)
    zuopinlii = []
    for i in zuopinli:
        zuopinlii.append({'name': i.bookName, "intro": i.intro, "id": i.id})
    return render(request, 'look.html', context={"zuopin": zuopinlii, 'dynasty': dyn[int(idd)]})


def putout(request):
    try:
        ck = request.get_signed_cookie(key='admin_name', salt="rxg")
        if ck == 'admin':
            pass
        else:
            return HttpResponse("账户名称不是admin")
    except Exception:
        return HttpResponse(reverse('web:background'))
    if request.method == 'POST':
        accountnumber = AccountNumber.objects.filter(account='admin').first()
        author = request.POST.get('author')
        book_name = request.POST.get('book_name')
        intro = request.POST.get('intro')
        translation = request.POST.get('translation')
        dynasty_id = request.POST.get('radiode')
        if dynasty_id is None:
            return HttpResponse("没有选朝代")
        dynasty = dyn[int(dynasty_id)]
        book_content = request.POST.get('book_content')
        bname = AllBook.objects.filter(bookName=book_name).first()  # 在数据库中查询是否有这本书了
        # uname = AccountNumber.objects.filter(number=user_name).first()
        if len(book_content) == 0:
            return HttpResponse("作品内容不能是空")
        if bname is None:
            print("内容是：", book_content)
            data = AllBook()
            data.upAccount = accountnumber
            data.bookName = book_name
            data.intro = intro
            data.translation = translation
            data.bookContent = book_content
            data.dynasty = dynasty
            data.author = author
            data.checkBool = 1
            data.save()
            return HttpResponse("发布成功")
        else:
            return HttpResponse('书名已经存在了')
    elif request.method == 'GET':
        return render(request, 'putout.html')


def myupload(request):
    try:  # 尝试获取cookies
        ck = request.get_signed_cookie(key='name', salt="rxg")
    except Exception:
        return HttpResponse(reverse('web:login'))
    try:
        name = request.get_signed_cookie(key='name', salt='rxg')
        username = AccountNumber.objects.filter(account=name).first().userName
        uploader = AccountNumber.objects.filter(account=ck).first()
        allhisbook = AllBook.objects.filter(upAccount=uploader)
        resault = []
        for i in allhisbook:
            if i.checkBool == 1:
                lii = {"n": i.bookName, 'r': '已经通过', 'rr': "感谢您的支持，您的作品好，已通过"}
                resault.append(lii)
            elif i.checkBool == 2:
                lii = {"n": i.bookName, 'r': '未审核', 'rr': "管理员繁忙，将尽快审核"}
                resault.append(lii)
            elif i.checkBool == 3:
                lii = {"n": i.bookName, 'r': '未通过', 'rr': i.pReason}
                resault.append(lii)
        return render(request, 'myupload.html', {'c': resault, 'name': username})
    except Exception:
        return HttpResponse("未知错误")


def lookpage(request, idd):
    if request.method == "GET":
        txt = AllBook.objects.filter(id=idd).first()
        book_id = txt.id
        author = txt.author
        cont = txt.bookContent
        bookname = txt.bookName
        translation = txt.translation
        intro = txt.intro
        dynasty = txt.dynasty
        conli = cont.split('\n')
        introli = intro.split('\n')
        translationli = translation.split('\n')  # 传递内容
        if txt is not None:
            book = AllBook.objects.filter(id=book_id).first()  # 根据书的id去获取书对象
            comm = Comment.objects.filter(bookName=book)  # 根据书对象获取评论对象
            commentli = []
            numm = 1
            for i in comm:
                ssss = AccountNumber.objects.filter(account=i.account).first().userName
                commentli.append({'name': ssss, "con": i.commentContent, 'num': numm, 'time': i.commenttime})
                numm = numm + 1
            con = {'name': bookname, 'author': author, 'dynasty': dynasty, "intro": introli,
                   'context': conli, 'translation': translationli, 'book_id': book_id, "connmentli": commentli,
                   }

            return render(request, 'lookpage.html', con)
        else:
            return HttpResponse("这本书不存在")
    elif request.method == "POST":
        try:
            ck = request.get_signed_cookie(key='name', salt="rxg")
        except Exception:
            return HttpResponseRedirect(reverse('web:homepage'))
        s = request.POST.get('comm')
        if len(s) == 0:
            return HttpResponse("你什么都没有输入")
        acc = AccountNumber.objects.filter(account=ck).first().account
        boo = AllBook.objects.filter(id=idd).first()
        Comment.objects.create(bookName=boo, account=acc, commentContent=s)
        return HttpResponseRedirect("web/lookpage/idd")
